import router from '@/router';
import { getUserDataCache, removeUserDataCache, toLogin, getToken } from '@/utils/app';
import axios from 'axios'
import { Dialog } from 'vant';

axios.defaults.withCredentials = true;
const api = axios.create({
  baseURL: 'http://localhost:9001/system',
  timeout: 10000,
  responseType: 'json',
  withCredentials: true
})

api.interceptors.request.use(
  request => {
    if (getUserDataCache() == null) {
      toLogin()
    }
    const token = getToken()
    if (token != null) {
      request.headers = {
        'content-Type': 'application/json;charset=utf-8',
        token: token
      }
    }
    return request
  }
)

api.interceptors.response.use(
  response => {
    const data = response.data
    if (data.code == 403) {
      Dialog({ message: '登录已失效,请重新登录' });
      removeUserDataCache()
      setTimeout(() => {
        toLogin()
      }, 1000);
    }

    return Promise.resolve(data)
  },
  error => {
    return Promise.reject(error)
  }
)

export default api
